<?php

namespace app\common\repositories;

class BaseRepository
{

    protected $dao;

    public function setDao($dao){
        $this->dao = $dao;
    }
    public function __call($name, $arguments)
    {
        return call_user_func_array([$this->dao, $name], $arguments);
    }

    /**
     * 更新
     */
    public function update($id,$data){
        return $this->dao->update($id,$data);
    }
    /**
     * create
     */    
    public function create($data){
        $entity =  $this->dao->create($data);
        return $entity->id ?? 0;
    }
    /**
     * @desc: 构建子查询
     * @author: xiaohp
     * @param {*} $where
     * @param {*} $field
     */
    public function getSubIdsQuerySql($where = [],$idField = 'id'){
        $subsql = $this->dao->search($where)->field($idField)->fetchSql(true)->select();
        $sql = $subsql . " UNION ALL SELECT '-1' WHERE NOT EXISTS ({$subsql})";
        return $sql;
    }
    /**
     * @desc: 获取主键且伴随新增或新建
     * @author: xiaohp
     * @param {*} $where
     * @param {*} $data
     * @param {*} $update
     */
    public function getPrimaryWithCreateOrUpdate($where,$data,$update){
        $info = $this->dao->search($where)->find();
        if($info){
            return $this->update($info->id,$update);
        }else{
            return $this->create($data);
        }
    }
    /**
     * @desc: 基于条件获取统计
     * @author: xiaohp
     * @param {*} $where
     */
    public function getStictisticsCountByWhere($where = []){
        return $this->dao->search($where)->count();
    }
    /**
     * @desc: 基于条件获取统计
     * @author: xiaohp
     * @param {*} $where
     */
    public function getStictisticsSumByWhere($where = []){
        return $this->dao->search($where)->sum('read_count');
    }

    /**
     * @desc: 获取主键值
     * @author: xiaohp
     * @param {*} $where
     */
    public function getPkValueByWhere($where = [],$pk = 'id'){
        $obj = $this->dao->search($where)->find();
        return $obj ? $obj->$pk : 0;
    }
}